#include "Sock.hpp"

void Usage(std::string proc)
{
  std::cout << "Usage: " << proc << "port" << std::endl;
}

void* HandlerRequest(void* arg)
{
  pthread_detach(pthread_self());

  std::pair<int, uint16_t> prams = *(std::pair<int, uint16_t>*)arg;
  int sockfd = prams.first;
  uint16_t port = prams.second;

  while(true){
    char buffer[1024];
    ssize_t s = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
    if(s > 0){
      buffer[s] = 0;
      std::cout << port << ": " << buffer << std::endl;
      send(sockfd, buffer, s, 0);
    }
  }
  close(sockfd);
}

int main(int argc, char* argv[])
{
  if(argc != 2){
    Usage(argv[0]);
    exit(1);
  }

  int listen_sockfd = Sock::Socket();
  std::cout << listen_sockfd << std::endl;
  Sock::Bind(listen_sockfd, atoi(argv[1]));
  Sock::Listen(listen_sockfd);
  
  while(true){
    int sockfd;
    Sock::Accept(listen_sockfd, sockfd);
    std::cout << "get a new link" << std::endl;

    pthread_t tid;
    std::pair<int, uint16_t> prams;
    prams.first = sockfd;
    prams.second = atoi(argv[1]);
    pthread_create(&tid, nullptr, HandlerRequest, (void*)&prams);
  }
  return 0;
}
